package com.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;


import vo.system.Oa_tymenu;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

public class Util {
	
	public static boolean isNullOrEmpty(Object obj) {	
		return obj == null || "".equals(obj.toString());
	}
	public static String toString(Object obj){
		if(obj == null) return "null";
		return obj.toString();
	}
	public static String join(Collection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
	public static String Encode(Object obj) {
		if(obj == null || obj.toString().equals("null")) return null;
		if(obj != null && obj.getClass() == String.class){
			return obj.toString();
		}
		JSONSerializer serializer = new JSONSerializer();
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Date.class);
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Timestamp.class);
		return serializer.deepSerialize(obj);
	}
	public static Object Decode(String json) {
		if (isNullOrEmpty(json)) return "";
		JSONDeserializer deserializer = new JSONDeserializer();
		//deserializer.use(String.class, new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"));		
		Object obj = deserializer.deserialize(json);
		if(obj != null && obj.getClass() == String.class){
			return Decode(obj.toString());
		}		
		return obj;
	}
	/**
	 * 功能：将输入字符串的首字母改成大写
	 * @param str
	 * @return
	 */
	public static String initcap(String str) {
		
		char[] ch = str.toCharArray();
		if(ch[0] >= 'a' && ch[0] <= 'z'){
			ch[0] = (char)(ch[0] - 32);
		}
		
		return new String(ch);
	}
	
	/**
	 * HashMap转换成vo对象
	 * @param str
	 * @return
	 */
	public static Object MapToVo(Object o,HashMap map) throws Exception {
		
		  Class<? extends Object> clazz = o.getClass();
		
		  Field[] fields = clazz.getDeclaredFields();
	
	
		 
			  // 循环遍历以获取的公开的属性
			 
			  for (int i = 0; i < fields.length; i++) {
				
				
				 // fields[1].getClass()  Integer.class
				  
				  
				//  String.class 
				  
				  
						
						String getFieldName = "set" + fields[i].getName();
						String name=String.valueOf(fields[i].getName());
						String datalx=String.valueOf(fields[i].getType());
						
						//System.out.println(datalx+"====");
						
						String val=null;
//						if("int".equals(datalx)||"class java.lang.String".equals(datalx))
//						{
						try{
							val=map.get(name.toLowerCase()).toString();
							if(null==val||"".equals(val))val=map.get(name.toUpperCase()).toString();
						}catch(Exception f)
						{
							val=null;
						}
//						}
						
						
						
						//System.out.println(fields[i].getName()+"===="+map.get(name.toLowerCase()));
						
						if(null==val||"".equals(val))
						{
							
						}
						else
						{
						try{
							clazz.getMethod(getFieldName, fields[i].getType()).invoke(o, val);
						}catch(Exception f)
						{
							try
							{
								int v=Integer.parseInt(val);
								clazz.getMethod(getFieldName, fields[i].getType()).invoke(o, v);
							}catch(Exception fs)
							{
								try
								{
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
									Date date1 = new Date();
									date1 = sdf.parse(val.replaceAll("T", " "));	
									clazz.getMethod(getFieldName, fields[i].getType()).invoke(o, date1);
								}catch(Exception gg)
								{
									try
									{
										byte[] b =val.getBytes();
										clazz.getMethod(getFieldName, fields[i].getType()).invoke(o, b);
									}catch(Exception gf)
									{
										
									}
								}
							}
						}
						}
						
			  }
			
			 
			  
		 
		  return o;
	}
	
	
	 public static String getObject(Object[] obj) 
	    {
	    	String flag="0";
	    	
	    	for(int i=0;i<obj.length;i++)
	    	{
	    		
	    		if("".equals(obj[i])||null==obj[i]){}
	    		else	{flag="1";break;}
	    	}
	    	
	    	return flag;
	    }
	    
		
	 /**
		 * 获取拼音码
		 * @param src
		 * @return
		 */
		 public static  String getPingYin(String src) {  
			  
		        char[] t1 = null;  
		        t1 = src.toCharArray();  
		        String[] t2 = new String[t1.length];
		        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();  
		          
		        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
		        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
		        t3.setVCharType(HanyuPinyinVCharType.WITH_V);  
		        String t4 = "";  
		        int t0 = t1.length;  
		        try {  
		            for (int i = 0; i < t0; i++) {  
		                // 判断是否为汉字字符  
		                if (java.lang.Character.toString(t1[i]).matches(  
		                        "[\\u4E00-\\u9FA5]+")) {  
		                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);  
		                    t4 += t2[0];  
		                } else  
		                    t4 += java.lang.Character.toString(t1[i]);  
		            }  
		            // System.out.println(t4);  
		            return t4;  
		        } catch (BadHanyuPinyinOutputFormatCombination e1) {  
		            e1.printStackTrace();  
		        }  
		        return t4;  
		    } 
	
		 	
		 /**
			 * 服务器excel表格下载到本地
			 * @param returnFile  服务器文件（file）	
			 * @param uploadedFileName  下载到本地的文件名
			 * @throws Exception
			 */
			  public static void downLoadData(HttpServletResponse response, File returnFile, String uploadedFileName)
			  {
			    response.reset();
			    response.setContentType("application/x-msdownload;charset=UTF-8");
			    response.setHeader("Content-Disposition", "attachment;filename=" + uploadedFileName);
			    
			    BufferedInputStream bis = null;
			    BufferedOutputStream bos = null;
			    
			    try
			    {
			    	bis = new java.io.BufferedInputStream(
							new java.io.FileInputStream(returnFile));
					bos = new java.io.BufferedOutputStream(
							response.getOutputStream());
			      byte[] buff = new byte[2048];
			      int bytesRead;
			      while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
			      {
			       
			        bos.write(buff, 0, bytesRead);
			      }
			    }
			    catch (Exception e)
			    {
			      e.printStackTrace();

			      if (bis != null)
			      {
			        try
			        {
			          bis.close();
			        }
			        catch (Exception e1)
			        {
			          e1.printStackTrace();
			        }
			      }
			      if (bos != null)
			      {
			        try
			        {
			          bos.close();
			        }
			        catch (IOException e1)
			        {
			          e1.printStackTrace();
			        }
			      }
			    }
			    finally
			    {
			      if (bis != null)
			      {
			        try
			        {
			          bis.close();
			        }
			        catch (IOException e)
			        {
			          e.printStackTrace();
			        }
			      }
			      if (bos != null)
			      {
			        try
			        {
			          bos.close();
			        }
			        catch (IOException e)
			        {
			          e.printStackTrace();
			        }
			      }
			    }
			  }
	
			  /** 
			   * 将存放在sourceFilePath目录下的源文件，打包成fileName名称的zip文件，并存放到zipFilePath路径下 
			   * @param sourceFilePath :待压缩的文件路径 
			   * @param zipFilePath :压缩后存放路径 
			   * @param fileName :压缩后文件的名称 
			   * @return 
			   */  
			  public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){  
				  boolean flag = false;  
				  File sourceFile = new File(sourceFilePath);  
				  FileInputStream fis = null;  
				  BufferedInputStream bis = null;  
				  FileOutputStream fos = null;  
				  ZipOutputStream zos = null;  

				  if(sourceFile.exists() == false){  
					  System.out.println("待压缩的文件目录："+sourceFilePath+"不存在.");  
				  }else{  
					  try {  
						  File zipFile = new File(zipFilePath + "/" + fileName +".zip");  
						  if(zipFile.exists()){  
							  System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  
						  }else{  
							  File[] sourceFiles = sourceFile.listFiles();  
							  if(null == sourceFiles || sourceFiles.length<1){  
								  System.out.println("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");  
							  }else{  
								  fos = new FileOutputStream(zipFile);  
								  zos = new ZipOutputStream(new BufferedOutputStream(fos));  
								  byte[] bufs = new byte[1024*10];  
								  for(int i=0;i<sourceFiles.length;i++){  
									  //创建ZIP实体，并添加进压缩包  
									  ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  
									  zos.putNextEntry(zipEntry);  
									  //读取待压缩的文件并写进压缩包里  
									  fis = new FileInputStream(sourceFiles[i]);  
									  bis = new BufferedInputStream(fis, 1024*10);  
									  int read = 0;  
									  while((read=bis.read(bufs, 0, 1024*10)) != -1){  
										  zos.write(bufs,0,read);  
									  }  
								  }  
								  flag = true;  
							  }  
						  }  
					  } catch (Exception e) {  
						  e.printStackTrace();  
						  throw new RuntimeException(e);  
					  } finally{  
						  //关闭流  
						  try {  
							  if(null != bis) bis.close();  
							  if(null != zos) zos.close();  
						  } catch (IOException e) {  
							  e.printStackTrace();  
							  throw new RuntimeException(e);  
						  }  
					  }  
				  }  
				  return flag;  
			  }  



}
